import { useEffect, useState, useRef, useCallback } from "react";

const useScroll = (ref) => {

  const frame = useRef(0);
  const [state, setState] = useState({
    offset: 0,
  });

  const setRafState = useCallback((value) => {
    cancelAnimationFrame(frame.current);

    frame.current = requestAnimationFrame(() => {
      setState(value);
    });
  }, []);

  const resetState = useCallback(() => {
    ref.current.scrollTop = 0;
    return {offset: 0, delta: 0}
  }, []);

  useEffect(() => {
    const handler = () => {
      if (ref.current) {
        const {scrollTop: curr} = ref.current;
        setRafState({
          offset: curr,
        });
      }
    };

    if (ref.current) {
      ref.current.addEventListener('scroll', handler, {
        capture: false,
        passive: true,
      });
    }

    return () => {
      cancelAnimationFrame(frame.current);
      if (ref.current) {
        ref.current.removeEventListener('scroll', handler);
      }
    };
  }, [ref]);

  return {state, resetState};
};

export default useScroll;